package database

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"go-gin-api/app/model"
	"go-gin-api/core/config"
	"go-gin-api/core/log"
	"go.uber.org/zap"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/plugin/dbresolver"
)

// 入口文件，描述在数据库的参数的

var db *gorm.DB // 指定原型
var err error   // 接收错误信息

func InitDB() {
	dsn := fmt.Sprintf("%s:%s@(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		config.GetString("mysql.user"),
		config.GetString("mysql.password"),
		config.GetString("mysql.host"),
		config.GetInt("mysql.port"),
		config.GetString("mysql.db"),
	)
	db, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		log.Error().Error("连接数据库失败", zap.Error(err))
		fmt.Printf("连接数据库失败。err=：%s", err)
	}
	//读写分离   gorm 会自动切换 读写
	db.Use(dbresolver.Register(dbresolver.Config{
		Sources:  []gorm.Dialector{mysql.Open(dsn)},
		Replicas: []gorm.Dialector{mysql.Open(dsn)},
		Policy:   dbresolver.RandomPolicy{},
	}))

	// 自动迁移。自动创建数据表，数据库表名自动加复数。//
	db.AutoMigrate(
		&model.User{},
	)

	//db.Close()
}

func GetContextDB(ctx *gin.Context) *gorm.DB {
	return db.WithContext(ctx)
}
func GetMasterDb() *gorm.DB {
	return db.Clauses(dbresolver.Write)
}
